%%%-------------------------------------------------------------------
%%% @author chenlong
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%% 聊天
%%% @end
%%% Created : 28. 三月 2019 14:18
%%%-------------------------------------------------------------------
-module(role_chat).
-author("chenlong").

-include("common.hrl").

%% API
-export([cs_chat_send/1]).

%%=============================EXPORTED FUNCTION=====================================
cs_chat_send(#cs_chat_send{channel = Channel, content = Content0}) ->
	Content = util:term_to_list(Content0),
	case lists:member(Channel,[?CHAT_CHANNEL_TYPE_WORLD,?CHAT_CHANNEL_TYPE_ROOM]) of
		?TRUE -> ok;
		_ ->
			?DEBUG("not exist that channel = ~p",[Channel]),
			throw(ok)
	end,
	CheckR = check_send(Channel),
	case CheckR of
		{ok, CDEndTime} ->
			?sendself(#sc_chat_send{result = 0, cdEndTime = CDEndTime}),
			%%执行广播
			do_chat_send(Channel,Content);
		{cd, CDEndTime} ->
			?sendself(#sc_chat_send{result = 1, cdEndTime = CDEndTime})
	end,
	ok.

%%=============================LOCAL FUNCTION=====================================
%%return Result
check_send(?CHAT_CHANNEL_TYPE_WORLD) ->
	Now = util:now(),
	CDEndTime = getChannelCD(?CHAT_CHANNEL_TYPE_WORLD),
	case Now >= CDEndTime of
		?TRUE ->
			CDTuple = data_chat:get(chat_cd),
			CD = element(1,CDTuple),
			setChannelCD(?CHAT_CHANNEL_TYPE_WORLD,Now+CD),
			{ok, Now+CD};
		_ -> {cd, CDEndTime}
	end;
check_send(?CHAT_CHANNEL_TYPE_ROOM) ->
	Now = util:now(),
	CDEndTime = getChannelCD(?CHAT_CHANNEL_TYPE_ROOM),
	case Now >= CDEndTime of
		?TRUE ->
			CDTuple = data_chat:get(chat_cd),
			CD = element(2,CDTuple),
			setChannelCD(?CHAT_CHANNEL_TYPE_ROOM,Now+CD),
			{ok, Now+CD};
		_ -> {cd, CDEndTime}
	end.

do_chat_send(?CHAT_CHANNEL_TYPE_WORLD, Content) ->
	#role{roleID = RoleID, roleName = RoleName}=role_data:getRole(),
	Fun = fun(MemberID) ->
		role_lib:sendToClient(MemberID,#sc_chat_content{channel = ?CHAT_CHANNEL_TYPE_WORLD,roleID = RoleID,roleName = RoleName,content = Content})
	      end,
	util:ets_foreach_key(Fun,?ETS_ROLE_ONLINE);
do_chat_send(?CHAT_CHANNEL_TYPE_ROOM, Content) ->
	#role{roleID = RoleID,roomID = RoomID, roleName = RoleName}=role_data:getRole(),
	EtsRoom=room_manager:getEtsRoom(RoomID),
	role_lib:broadcastToClient(EtsRoom,#sc_chat_content{channel = ?CHAT_CHANNEL_TYPE_ROOM,roleID = RoleID,roleName = RoleName,content = Content}).

%%=============================INNER FUNCTION=====================================
getChannelCD(Channel) ->
	#chat{cdList = CDList}=getChat(),
	case lists:keyfind(Channel,1,CDList) of
		{_,CD} -> CD;
		_ -> 0
	end.
setChannelCD(Channel, CDEndTime) ->
	#chat{cdList = CDList}=Chat=getChat(),
	CDList1 = lists:keystore(Channel,1,CDList,{Channel,CDEndTime}),
	setChat(Chat#chat{cdList = CDList1}).

getChat() ->
	case get(?ROLE_CHAT) of
		#chat{}=Chat -> Chat;
		_ -> #chat{}
	end.
setChat(Chat) -> put(?ROLE_CHAT,Chat).